﻿// 开发者:micropu
// 公司:佛山远钧智慧科技有限公司

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.NET.Application;

/// <summary>
/// 会话断开
/// </summary>
public class ClientDisconnectedPlugin : ITcpDisconnectedPlugin
{
    public void Dispose()
    {
        Console.WriteLine("执行与释放、释放或重置非托管资源相关的应用程序定义的任务。");
    }

    public void Loaded(IPluginManager pluginManager)
    {
        Console.WriteLine("在插件被成功添加在IPluginManager时执行");
    }

    public Task OnTcpDisconnected(ITcpClientBase client, DisconnectEventArgs e)
    {
        var webSocketManager = App.GetService<IClientWebSocketManager>();
        var _connections = webSocketManager.SelectAllConnections();
        // 在 _connections 中查找 client 的设备号
        foreach (var item in _connections)
        {
            if (item.Value == client)
            {
                if (_connections.TryGetValue(item.Key, out var webSocket))
                {
                    _connections.Remove(item.Key, out webSocket);
                    webSocket.SafeClose();
                }
                break;
            }
        }
        return Task.CompletedTask;
    }
}
